﻿using System;
using NJabber.Client.StanzaFactories;
using NJabber.Stream;
using NJabber.Stream.Elements;
using System.Collections.Generic;

namespace NJabber.Client
{
    public class RosterUpdater : IRosterUpdater
    {
        private IXmppConnection connection;
        private IRosterStanzaFactory factory;

        public RosterUpdater(IXmppConnection connection, IRosterStanzaFactory factory)
        {
            this.connection = connection;
            this.factory = factory;
        }

        public void Update(RosterChanges changes)
        {
            if (changes == null) throw new ArgumentNullException("changes");

            SendAddedItems(changes);
            SendChangedItems(changes);
            SendRemovedItems(changes);
        }

        private void SendAddedItems(RosterChanges changes)
        {
            SendItems(changes.AddedItems, item => factory.CreateAddRosterItemRequest(item, connection.Jid));
        }

        private void SendChangedItems(RosterChanges changes)
        {
            SendItems(changes.ChangedItems, item => factory.CreateUpdateRosterItemRequest(null, item, connection.Jid));
        }

        private void SendRemovedItems(RosterChanges changes)
        {
            SendItems(changes.RemovedItems, item => factory.CreateDeleteRosterItemRequest(item, connection.Jid));
        }

        private void SendItems(IEnumerable<RosterItem> items, Func<RosterItem, Stanza> factory)
        {
            foreach (RosterItem item in items)
            {
                Stanza stanza = factory(item);
                SendStanza(stanza);
            }
        }

        private void SendStanza(Stanza stanza)
        {
            connection.Stream.Write(stanza);
        }        
    }
}
